package edu.umn.contactviewer;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import edu.umn.contactviewer.datastore.ContactListDataService;
import edu.umn.contactviewer.datastore.ContactListDataService.RequestResult;
import edu.umn.contactviewer.datastore.CreateContactRequestResponseListener;
import edu.umn.contactviewer.datastore.impl.ContactListDataServiceRESTWebServiceImpl;

public class CreateActivity extends Activity {
	private static final int FOREGROUND_COLOR = -16777216;
	private int MINIMUM_NAME_LENGTH;

	private final ContactListDataService contactListDataStore;
	private EditText nameTextView = null;

	public CreateActivity() {
		contactListDataStore = new ContactListDataServiceRESTWebServiceImpl(
				this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create);
		new EditToolbar();

		// init constant from resource file
		MINIMUM_NAME_LENGTH = getResources().getInteger(
				R.integer.minimum_name_length);

		// attach text change listener to the name field to enable validation
		nameTextView = (EditText) findViewById(R.id.edit_name);
		nameTextView.addTextChangedListener(new TextWatcher() {

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// empty implementation
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// empty implementation
			}

			public void afterTextChanged(Editable s) {
				validateNameTextField();
			}
		});
	}

	private boolean validateNameTextField() {
		// name field is valid
		boolean isNameTextFieldIsValid = (nameTextView.getText().toString()
				.length() >= MINIMUM_NAME_LENGTH);
		if (!isNameTextFieldIsValid) {
			String errorString = getString(R.string.name_validation_error_string);
			ForegroundColorSpan fSpan = new ForegroundColorSpan(
					FOREGROUND_COLOR);
			SpannableStringBuilder ssBuilder = new SpannableStringBuilder(
					errorString);
			ssBuilder.setSpan(fSpan, 0, errorString.length(), 0);
			nameTextView.setError(ssBuilder);
		}

		return isNameTextFieldIsValid;
	}

	private Contact retrieveContactToSave() {
		EditText nameTextView = (EditText) findViewById(R.id.edit_name);
		Contact contactToSave = new Contact(nameTextView.getText().toString());

		EditText titleTextView = (EditText) findViewById(R.id.edit_title);
		contactToSave.setTitle(titleTextView.getText().toString());

		EditText phoneTextView = (EditText) findViewById(R.id.edit_phone);
		contactToSave.setPhone(phoneTextView.getText().toString());

		EditText emailTextView = (EditText) findViewById(R.id.edit_email);
		contactToSave.setEmail(emailTextView.getText().toString());

		EditText twitterIdTextView = (EditText) findViewById(R.id.edit_twitterid);
		contactToSave.setTwitterId(twitterIdTextView.getText().toString());

		return contactToSave;
	}

	private boolean createdFieldsValid() {
		return validateNameTextField();
	}

	private class EditToolbar extends ToolbarConfig {
		public EditToolbar() {
			super(CreateActivity.this, getString(R.string.create));
			Button rightButton = getToolbarRightButton();
			rightButton.setText(getString(R.string.save));
			rightButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if (createdFieldsValid()) {
						Contact contactToSave = retrieveContactToSave();
						contactListDataStore.storeContact(contactToSave,
								new CreateContactRequestResponseListener() {
									public void onCreateContactResponse(
											RequestResult createContactRequestResponse) {
										if (createContactRequestResponse
												.equals(RequestResult.SUCCESS)) {
											showToast(getString(R.string.save_success_message));
											setResult(RESULT_OK);
											finishActivity();
										} else {
											showToast(getString(R.string.save_error_message));
										}
									}
								});
					}// end if (createdFieldsValid())
				}
			});
			rightButton.setVisibility(View.VISIBLE);
		}
	}

	private void showToast(String toastText) {
		Toast.makeText(getApplicationContext(), toastText, 5).show();
	}
}
